package com.zx.mes.hyl.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zx.mes.controller.BaseController;
import com.zx.mes.hyl.entity.SysRole;
import com.zx.mes.hyl.entity.SysRoleMenu;
import com.zx.mes.hyl.entity.SysUserRole;
import com.zx.mes.hyl.pagemodel.TreeNode;
import com.zx.mes.hyl.service.SysRoleMenuService;
import com.zx.mes.hyl.service.SysRoleService;
import com.zx.mes.hyl.service.SysUserRoleService;
import com.zx.mes.response.ObjectRestResponse;
import com.zx.mes.response.TableResultResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 华云龙
 * @since 2018-07-09
 */
@CrossOrigin
@RestController
@RequestMapping("/sysRole")
public class SysRoleController extends BaseController<SysRoleService,SysRole>{

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public ObjectRestResponse<SysRole> add(SysRole sysRole) {
        sysRole.setId(UUID.randomUUID().toString());
        return super.add(sysRole);
    }

    @Override
    public TableResultResponse<SysRole> list(@RequestParam Map<String, Object> params, SysRole sysRole) {
        int page = Integer.valueOf(params.get("page").toString());
        int limit = Integer.valueOf(params.get("limit").toString());

        Wrapper<SysRole> wrapper = new EntityWrapper<>();
        if (sysRole != null && !"".equals(sysRole.getName())) {
            wrapper.like("name", sysRole.getName());
        }

        List<SysRole> list = this.biz.selectPage(new Page(page, limit),wrapper).getRecords();
        TableResultResponse<SysRole> response = null;
        if (list == null) {
            response = new TableResultResponse("无数据", 200, 0L, (long)page, (List)null);
        } else {
            response = new TableResultResponse("分页查询结果", 200, (long)this.biz.selectCount(new EntityWrapper()), (long)page, list);
        }

        return response;

    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/grantMenu")
    public ObjectRestResponse grantMenu(String roleId,String menuIds){
        ObjectRestResponse response = new ObjectRestResponse();
        String[] ids = menuIds.split(",");
        List<SysRoleMenu> list = new ArrayList<>();
        for (int i = 0; i <ids.length ; i++) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setId(UUID.randomUUID().toString());
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(ids[i]);
            list.add(sysRoleMenu);
        }
        /// 对已存在的角色进行授权，只需要对中间表进行操作
        try {
            sysRoleMenuService.insertBatch(list, list.size());
            response.setMessage("角色授权成功!");
        } catch (Exception e) {
            response.setStatus(500);
            response.setMessage("角色授权失败:"+e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/deleteBatch")
    public ObjectRestResponse<String> deleteBatch(String ids) {
        ObjectRestResponse<String> response = new ObjectRestResponse<>();
        try {
            /// 删除sysRole表中的数据
            biz.deleteBatchIds(Arrays.asList(ids.split(",")));
            /// 删除sysUserRole表中对应的数据
            sysUserRoleService.delete(new EntityWrapper<SysUserRole>()
                    .in("role_id", ids));
            /// 删除sysRoleMenu表中对应的数据
            sysRoleMenuService.delete(new EntityWrapper<SysRoleMenu>()
                    .in("role_id", ids));
        } catch (Exception e) {
            response.setMessage(e.getMessage());
            response.setStatus(500);
            e.printStackTrace();
        }
        response.setMessage("批量删除成功!");
        return response;
    }

    /**
     * 角色 树结构获取
     * @return
     */
    @GetMapping("/treeNodesRole")
    public TableResultResponse<TreeNode> treeNodesRole(){
        TableResultResponse<SysRole> response = new TableResultResponse<>();
        /// 获取所有的角色
        List<SysRole> roleList = biz.selectList(new EntityWrapper<>());
        List<TreeNode> list = new ArrayList<>();
        List<TreeNode> nodeList = new ArrayList<>();
        /// 将集合类型进行转换 SysRole --> TreeNode
        for (int i = 0; i <roleList.size() ; i++) {
            TreeNode treeNode = new TreeNode();
            SysRole sysRole = roleList.get(i);
            treeNode.setId(sysRole.getId());
            treeNode.setKey(sysRole.getId());
            treeNode.setTitle(sysRole.getName());
            treeNode.setValue(sysRole.getId());
            treeNode.setPid(sysRole.getPid());
            nodeList.add(treeNode);
        }
        /// 做递归操作
        for (int i = 0; i <nodeList.size() ; i++) {
            TreeNode node = nodeList.get(i);
            if (!StringUtils.isNotBlank(node.getPid())) {
                list.add(getChildNodes(nodeList, node));
            }
        }
        return new TableResultResponse<>(0,0,list);
    }

    /**
     * 递归的具体操作
     * @param nodeList nodeList
     * @param treeNode treeNode
     * @return TreeNode
     */
    private TreeNode getChildNodes(List<TreeNode> nodeList, TreeNode treeNode) {
        for (int i = 0; i <nodeList.size() ; i++) {
            TreeNode node = nodeList.get(i);
            if (StringUtils.isNotBlank(node.getPid()) && node.getPid().equals(treeNode.getId())) {
                treeNode.getChildren().add(node);
                getChildNodes(nodeList, node);
            }
        }
        return treeNode;
    }
}

